package com.gitee.deeround.jdbchelper.core.impl;

import com.gitee.deeround.jdbchelper.core.DbActionExt;
import com.gitee.deeround.jdbchelper.core.Dialect;
import com.gitee.deeround.jdbchelper.core.DialectHelper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class DbActionExtImpl extends BaseDbAction implements DbActionExt {

    private final JdbcTemplate jdbcTemplate;

    public DbActionExtImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void mergeInto(String tableName, String newData, String idColumn, List<String> insertColumns, List<String> updateColumns) {
        Dialect dialect = DialectHelper.getDialect(jdbcTemplate);
        List<String> sqls = dialect.mergeInto(tableName, newData, idColumn, insertColumns, updateColumns);
        for (String sql : sqls) {
            jdbcTemplate.update(sql);
        }
    }

    @Override
    public void mergeInto(String tableName, String newData, String idColumn, List<String> insertColumns, List<String> updateColumns, Object[] ps) {
        Dialect dialect = DialectHelper.getDialect(jdbcTemplate);
        List<String> sqls = dialect.mergeInto(tableName, newData, idColumn, insertColumns, updateColumns);
        for (String sql : sqls) {
            if (ps != null && ps.length > 0) {
                jdbcTemplate.update(sql, ps);
            } else {
                jdbcTemplate.update(sql);
            }
        }
    }

    @Override
    public String recursiveSub(String tableName, String idColumn, String pidColumn, List<String> columns, String idValue) {
        Dialect dialect = DialectHelper.getDialect(jdbcTemplate);
        return dialect.recursiveSub(tableName, idColumn, pidColumn, columns, idValue);
    }
}
